# This class defines a method to calculate the maximum distance between two elements from a list of
# lists of integers.
from typing import *
from math import inf


class Solution:
    def maxDistance(self, arrays: List[List[int]]) -> int:
        m = len(arrays)
        mns = [inf] * m
        mxs = [-inf] * m
        for i in range(m - 2, -1, -1):
            mns[i] = min(arrays[i + 1][0], mns[i + 1])
            mxs[i] = max(arrays[i + 1][-1], mxs[i + 1])
        ans = 0
        mn, mx = inf, -inf
        for i in range(m):
            a, b = arrays[i][0], arrays[i][-1]
            if i < m - 1:
                ans = max(ans, abs(a - mns[i]), abs(a - mxs[i]))
                ans = max(ans, abs(b - mns[i]), abs(b - mxs[i]))
            if i > 0:
                ans = max(ans, abs(a - mn), abs(a - mx))
                ans = max(ans, abs(b - mn), abs(b - mx))
            mn, mx = min(mn, a), max(mx, b)
        return ans


s = Solution()
print(s.maxDistance([[1, 2, 3], [4, 5], [1, 2, 3]]))
